<template>
    <div class="archiveMail">
        <Modal
            width="82%"
            v-model="archiveMailModel"
            :footer-hide="true"
            :open-model="archiveMailModel=true"
            @on-cancel="cancelArchiveMail"
        >
            <div style="background:white;padding:20px" class="archiveMailInfo">
                <Row>
                    <Col span="5">
                        <h2 class="mb10">客户信息</h2>
                        <ul class="customInfo">
                            <li>申请编号:<span>{{customInfo.camainNo}}</span></li>
                            <li>客户姓名:<span>{{customInfo.borrowerName}}</span></li>
                            <li>证件号码:<span>{{customInfo.card}}</span></li>
                            <li>VIN码:<span>{{customInfo.vin}}</span></li>
                            <li>贷款金额:<span>{{customInfo.loanmoney}}</span></li>
                            <li>归档状态:<span>{{customInfo.statusfilenamename}}</span></li>
                        </ul>
                    </Col>
                    <Col span="16" offset="1">
                        <Form ref="fileMsgForm" :model="fileMsgForm">
                            <div class="common_br">
                                <h2 class="common_title">车辆信息</h2>
                                <div class="common_content">
                                    <Row>
                                        <Col span="10">
                                            <FormItem label="车牌号" prop="plateNo"
                                                      :rules="isCheckAutomobile?plateNoValiate:notPlateNoValiate">
                                                <Input v-model="fileMsgForm.plateNo" placeholder="请输入" class="w200"
                                                       :disabled="!isAutomobile"/>
                                            </FormItem>
                                        </Col>
                                        <Col span="10">
                                            <FormItem label="抵押登记日期" prop="pledgeDate"
                                                      :rules="isCheckAutomobile?pledgeDateValiate:notPledgeDateValiate">
                                                <DatePicker type="date" class="w200" v-model="fileMsgForm.pledgeDate"
                                                            placeholder="请选择抵押登记日期" :options="fisrstPledgeDate"
                                                            :disabled="!isAutomobile"></DatePicker>
                                            </FormItem>
                                        </Col>
                                    </Row>
                                </div>
                            </div>
                            <div class="common_br">
                                <h2 class="common_title">归档资料
                                    <Checkbox
                                        :indeterminate="indeterminate"
                                        :value="checkAll"
                                        @click.prevent.native="handleCheckAll" class="fr" style="padding-right: 30px;"
                                        v-if="categoryList.length>0" :disabled="isforbidAll">全选
                                    </Checkbox>
                                </h2>
                                <div class="common_content">
                                    <div class="archiveList" style="width:85%;position: relative;">
                                        <CheckboxGroup v-model="checkAllGroup" @on-change="checkAllGroupChange"
                                                       class="inline-block">
                                            <Checkbox :label="item.code" v-for="(item,index) in categoryList"
                                                      class="mb10" :disabled="item.ischeck==1">{{item.name}}
                                            </Checkbox>
                                        </CheckboxGroup>
                                        <Checkbox v-model="tempOtherdata.isothercheck"
                                                  v-if='Object.keys(tempOtherdata).length>0' @on-change="checkOther"
                                                  :disabled="tempOtherdata.ischeck==1">
                                            {{tempOtherdata.name}}
                                            <Input v-model="fileMsgForm.otherName" placeholder="请输入" class="w200"
                                                   maxlength="64" :disabled="tempOtherdata.ischeck==1"/>
                                        </Checkbox>
                                    </div>
                                </div>
                                <div v-if="isupload" class="over mt10">
                                    <div class="upload fl">
                                        <div class="upimg">
                                            <input type="file" name="file1" @change="uploadImg" ref="uploadInput">
                                            上传图片
                                        </div>
                                    </div>
                                    <ul class="showImg fl over">
                                        <li v-for="(item,index) in imgurlList" class="fl">
                                            <img :src="'data:image/jpeg;base64,'+item.imgurl" alt="" width="100"
                                                 height="100"/>
                                            <Icon type="ios-trash-outline" style="font-size:20px;cursor: pointer;"
                                                  @click="deleteImg(item.randomStr)"/>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                            <div style="text-align: center;margin-top: 20px;">
                                <Button type="primary" size="small" style="margin-right: 5px" @click="submit">提交
                                </Button>
                                <Button type="primary" size="small" @click="cancelArchiveMail">返回</Button>
                            </div>
                        </Form>
                    </Col>
                </Row>
            </div>
        </Modal>
    </div>
</template>
<script>
    import {docInfo} from "@/projects/afs-apply/assets/js/staticData.js"
    import {
        editDocInfo,
        submitDocInfo,
        uploadFile,
        delImage
    } from "_p/afs-apply/api/mail-manage/orderMailList.js";
    import {deepClone} from "@/libs/utils/ObjectClone";
    import LeaseFileUpload from '_c/file-upload/index';
    import {formatDate} from "@/components/iview/components/date-picker/util";

    export default {
        name: "archiveMail",
        data() {
            return {
                tempData: {},
                tempOtherdata: {},
                customInfo: {},
                modal: true,
                archiveMailModel: false,
                indeterminate: false,
                checkAll: false,
                checkAllGroup: [],
                checkDisabledGroup: [],
                tempAllGroup: [],
                categoryList: [],
                isAutomobile: false,
                isforbidAll: false,
                isCheckAutomobile: false,
                imgurlList: [],
                isOther: false,
                isupload: false,
                fileMsgForm: {
                    plateNo: "",
                    mortRegister: "",
                    otherName: "",
                },
                fisrstPledgeDate: {
                    disabledDate(date) {
                        return date && date.valueOf() > Date.now() - 8.64e6;
                    }
                },
                plateNoValiate: [
                    {required: true, message: "车牌号不能为空", trigger: "blur"}
                ],
                notPlateNoValiate: [
                    {required: false, message: "车牌号不能为空", trigger: "blur"}
                ],
                pledgeDateValiate: [
                    {required: true, message: "抵押登记日期不能为空", trigger: "change", type: "date"}
                ],
                notPledgeDateValiate: [
                    {required: false, message: "抵押登记日期不能为空", trigger: "change", type: "date"}
                ]
            }
        },
        components: {
            LeaseFileUpload,
        },
        props: {
            // archiveMailType:{
            //     type:String,
            // },
            cacontractId: {
                type: String
            },
            id: {
                type: String,
            },
            postId: {
                type: String,
            }
        },
        watch: {},
        mounted() {
            this.modifyDocInfo();
        },
        methods: {
            // 编辑查看归档信息
            modifyDocInfo(type) {
                let params = {
                    cacontractId: this.cacontractId,
                    isEdit: true,
                    isNotPost: true,
                }
                console.log(params, "params")
                editDocInfo(params).then(res => {
                    // let res=docInfo;
                    if (res.code == "0000") {
                        if (type != 'part') {
                            this.tempData = deepClone(res.data)
                            console.log(res.data.refData, "statusfilenamename")
                            let obj = {
                                camainNo: res.data.contract.camainNo,
                                borrowerName: res.data.contract.borrowerName,
                                card: res.data.contract.card,
                                vin: res.data.contract.vin,
                                loanmoney: res.data.contract.loanmoney,
                                statusfilenamename: res.data.contract.refData.statusfilenamename,
                            }
                            this.customInfo = obj;
                            this.categoryList = [];
                            this.checkAllGroup = [];
                            // 其他
                            let tempOtherdata = {};
                            if (res.data.categoryList.length > 0) {
                                for (let i = 0; i < res.data.categoryList.length; i++) {
                                    if (res.data.categoryList[i].code == "1101" || res.data.categoryList[i].code == "3601") {
                                        this.isAutomobile = true;
                                        break;
                                    }
                                }
                                // for(let i=0;i<res.data.categoryList.length;i++){
                                //     if(res.data.categoryList[i].ischeck=="1"){
                                //         this.isforbidAll=true;
                                //         break;
                                //     }
                                // }
                            }
                            res.data.categoryList.forEach((item, index) => {
                                if (item.code != "9901") {
                                    let obj = {
                                        name: item.name,
                                        code: item.code,
                                        ischeck: item.ischeck
                                    }
                                    this.categoryList.push(obj);
                                    if (item.ischeck) {
                                        this.checkAllGroup.push(item.code);
                                    }
                                    if (item.ischeck == '1') {
                                        this.checkDisabledGroup.push(item.code)
                                    }
                                } else if (item.code == "9901") {
                                    tempOtherdata.code = item.code;
                                    tempOtherdata.name = item.name;
                                    tempOtherdata.ischeck = item.ischeck;
                                    tempOtherdata.isothercheck = item.ischeck == 1 ? true : false;
                                }

                            })
                            console.log(this.checkDisabledGroup, res.data.categoryList, "res.data.categoryList")
                            this.tempAllGroup = this.checkAllGroup;
                            // 判断回显选中是否有机动车
                            if (this.tempAllGroup.indexOf('1101') != "-1" || this.tempAllGroup.indexOf('3601') != "-1") {
                                this.isupload = true;
                                this.isCheckAutomobile = true;
                            } else {
                                this.isupload = false;
                                this.isCheckAutomobile = false;
                            }
                            // 判断其他的复选按钮是否存在
                            if (Object.keys(tempOtherdata).length > 0) {
                                this.isOther = true;
                                // this.categoryList.push(tempOtherdata);
                                // console.log(this.categoryList,"this.categoryList")
                            } else {
                                this.isOther = false;
                            }
                            this.tempOtherdata = tempOtherdata

                            this.fileMsgForm.otherName = res.data.otherName || ''
                            this.checkAllGroupChange(this.checkAllGroup);

                            // 有机动车的时候回显车辆信息
                            if (this.isAutomobile) {
                                this.fileMsgForm.plateNo = res.data.after.plateNo || '';
                                this.fileMsgForm.pledgeDate = res.data.after.pledgeDate || ''
                            }
                        }
                        // 回显图片
                        let imgurlList = [];
                        if (res.data.md5List.length > 0) {
                            res.data.md5List.forEach((item, index) => {
                                // const blob = new Blob([item.md5Byte],{ type: 'image/jpeg' })
                                // let imgurl = window.URL.createObjectURL(blob);
                                let obj = {
                                    imgurl: item.md5Byte,
                                    randomStr: item.randomStr,
                                    // id:item.id
                                }
                                imgurlList.push(obj);
                                this.imgurlList = imgurlList;
                            })
                        } else {
                            this.imgurlList = imgurlList;
                        }
                    }
                })
            },
            cancelArchiveMail() {
                this.$emit("close-archiveMail-model", false, "cancel")
            },
            getArrDifference(arr1, arr2) {
                return arr1.concat(arr2).filter(function (v, i, arr) {
                    return arr.indexOf(v) === arr.lastIndexOf(v);
                });
            },
            checkOther(val) {
                if (!val) {
                    this.fileMsgForm.otherName = "";
                }
            },
            handleCheckAll() {
                if (this.indeterminate) {
                    this.checkAll = false;
                } else {
                    this.checkAll = !this.checkAll;
                }
                this.indeterminate = false;

                if (this.checkAll) {
                    // console.log(this.categoryList,"1111")
                    let codeList = this.categoryList.map((item, index) => {
                        return item.code;
                    })
                    this.checkAllGroup = codeList;
                    this.checkAllGroupChange(this.checkAllGroup)
                } else {
                    // this.checkAllGroup = [];
                    this.checkAllGroup = this.checkDisabledGroup;
                    this.checkAllGroupChange(this.checkAllGroup)
                }
            },
            checkAllGroupChange(data) {
                console.log(data, "data")
                // 全选
                if (data.length === this.categoryList.length) {
                    this.indeterminate = false;
                    this.checkAll = true;
                    // 半选
                }
                // else if (data.length > 0) {
                //     this.indeterminate = true;
                //     this.checkAll = false;
                // // 全不选
                // }
                else {
                    this.indeterminate = false;
                    this.checkAll = false;
                }
                console.log(this.indeterminate, this.checkAll)
                var proid = this.getArrDifference(data, this.tempAllGroup);
                // console.log(proid,"proid")
                this.tempAllGroup = data;
                // 选中机动车的复选框
                if (proid.length > 0) {
                    proid.forEach((item, index) => {
                        if (item == "1101" || item == "3601") {
                            if (data.indexOf(proid[0]) != "-1") {
                                this.isupload = true;
                                this.isCheckAutomobile = true;
                                // 反选某个复选框
                            } else {
                                this.isupload = false;
                                this.isCheckAutomobile = false;
                                // console.log("取消")
                            }
                        }
                    })
                }
            },
            deleteImg(randomStr) {
                let params = {
                    randomStr: randomStr,
                }
                delImage(params).then(res => {
                    if (res.code === "0000") {
                        this.modifyDocInfo('part');
                    }
                });
            },
            uploadImg() {
                let files = this.$refs.uploadInput.files;
                let AllUpExt = ".jpg|.bmp|.jpeg|.png|.gif|";
                let extName = files[0].name.substring(files[0].name.lastIndexOf(".")).toLowerCase();
                if (AllUpExt.indexOf(extName + "|") == "-1") {
                    this.$Message.warning("文件格式不正确！");
                    return;
                }

                let size = files[0].size;
                size = size / (1024 * 1024);
                console.log(size)
                if (size > 10) {  // 10M
                    this.$Message.warning("文件过大");
                    return;
                }

                let file = files[0];
                let formData = new FormData();//创建 formdata对象
                formData.append('file', file);
                formData.append('cacontractId', this.cacontractId);
                if (this.checkAllGroup.length > 0) {
                    this.checkAllGroup.forEach((item, index) => {
                        if (item == '1101' || item == "3601") {
                            formData.append('imCategoryCode', item);
                        }
                    })
                }
                console.log(this.checkAllGroup, "checkAllGroup");
                uploadFile(formData).then(res => {
                    this.$Message.success("上传成功");
                    this.modifyDocInfo('part')
                });

            },

            submit() {
                this.$refs.fileMsgForm.validate((valid) => {
                    if (valid) {
                        let pledgeDate = formatDate(this.fileMsgForm.pledgeDate, "yyyy-MM-dd");
                        let params = {
                            cacontractId: this.cacontractId,                //类型：String  必有字段  备注：合同ID（前端用）
                            applicationNo: this.tempData.contract.camainNo,                //类型：String  必有字段  备注：申请编号对应前台原camainno（前端用）
                            plateNo: this.fileMsgForm.plateNo,                //类型：String  必有字段  备注：caafter表车牌号对应前台原after.plateno（前端用）
                            pledgeDate: pledgeDate,                //类型：String  必有字段  备注：pledgedate抵押登记时间对应前台原after.pledgedate（前端用）
                            dcpostId: this.id,                //类型：String  必有字段  备注：DCPOST邮寄信息表id对应前台原postfile.dcpostid（前端用）
                            dcpostFileOthername: '',                //类型：String  必有字段  备注：DCPOSTFILE邮寄列表othername(其他)字段对应前台原othername（前端用）
                            isCheckLv: true,                //类型：Boolean  必有字段  备注：是否lv挂靠(前端用)
                            postId: this.id,
                        };
                        let codes = "";
                        let names = "";
                        if (!this.tempOtherdata.isothercheck) {
                            if (!this.fileMsgForm.otherName) {
                                this.$Message.warning("请填写其他复选按钮的文本框");
                                return;
                            }
                            codes = "9901" + ',';
                            names = "其他" + ",";
                            params.dcpostFileOthername = this.fileMsgForm.otherName
                        }
                        this.categoryList.forEach((item, index) => {
                            // 不为选中禁止状态
                            if (item.ischeck != "1") {
                                if (this.checkAllGroup.indexOf(item.code) != -1) {
                                    codes += item.code + ','
                                    names += item.name + ',';
                                }
                            }
                        })
                        params.codes = codes.substring(0, codes.length - 1);
                        if (!params.codes) {
                            this.$Message.warning("归档资料不能为空");
                            return;
                        }
                        params.dcpostFileNames = names.substring(0, names.length - 1);
                        submitDocInfo(params).then(res => {
                            if (res.code == "0000") {
                                this.$Message.success("提交归档信息成功");
                                this.$emit("close-archiveMail-model", false, "submit")
                            }
                        })
                    }
                })
            }
        }
    }
</script>
<style scoped>
    .archiveMailInfo .customInfo {
        padding-left: 20px;
    }

    .archiveMailInfo .customInfo > li {
        margin-bottom: 15px;
    }

    .upload {
        width: 100px;
        height: 100px;
        border: 1px dotted #ccc;
        position: relative;
    }

    .upimg {
        width: 80px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        background: #EB9620;
        border-radius: 5px;
        color: #FFFFFF;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }

    .upimg:hover {
        background: #EB9620;
        text-decoration: none;
    }

    .upimg input {
        position: absolute;
        left: 0;
        right: 0;
        width: 100%;
        top: 0;
        bottom: 0;
        height: 100%;
        filter: alpha(opacity=0);
        opacity: 0;
        cursor: pointer;
        overflow: hidden;
    }

    .showImg i {
        position: absolute;
        right: 0;
        bottom: 0;
    }

    .showImg > li {
        width: 100px;
        height: 100px;
        position: relative;
        border: 1px dotted #ccc;
        margin-left: 10px;
    }

    .showImg > li img {
        width: 100%;
        height: 100%;
    }
</style>
